<?php


namespace app\service;

use app\model\ModelReceivable;
use app\model\ModelUserAccountCard;
use app\model\ModelUserAccountCost;
use app\model\ModelUserAccountIncome;
use app\model\ModelUserAccountPopularize;
use app\model\ModelUserAccountRechange;
use app\model\ModelUserAccountTaskComplete;
use think\db\Query;
use think\facade\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

use app\model\ModelUserAccount;

/**
 * 用户账号相关服务类
 * Class UserAccountService
 * @package app\service
 */
class UserAccountService extends BaseService
{

    /**
     *
     * @param int $profit
     * @param int $userId
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setTotalTaskProfit(int $profit, int $userId) {
        $userAccountModel = new ModelUserAccount();
        $currentTotalTaskProfit = $userAccountModel->find($userId);
    }

    /**
     * 根据用户ID 获取用户账号基本信息
     * @param int $user_id
     * @param string $field 查询字段，默认*
     * @return array
     */
    public function getUserAccountByUerID(int $user_id,string $field ='*') : array {
        if(empty($user_id)){
            return $this->error('参数错误');
        }
        $userAccountModel = new ModelUserAccount();
        $result = $userAccountModel -> where('user_id',$user_id)
            ->field($field)
            ->findOrEmpty()
            ->toArray();
        return $this->success('成功', $result);
    }

    /**
     * 给用户账号充值
     * @param int $user_id 用户ID
     * @param string $amount 充值金额，必填，大于0且不大于100000
     * @param int $type 充值渠道类型，101 银行卡，201 微信，301 支付宝
     * @param int $business_type 业务类型: 101:充值；201:任务；301:推广；401:团队
     * @param int $vip_lv 非必填，如果业务类型是101，则需要传回用户VIP级别
     * @param int $receivable_id 平台收款的信息ID不可为空
     * @return array
     * @throws DbException
     */
    public function userChongZhi(int $user_id,string $amount,int $type,int $business_type,int $vip_lv=0,int $receivable_id) : array
    {
        //dump($user_id,$amount,$type,$pic_url);die();
        if (empty($user_id) || empty($amount) || empty($type) || empty($business_type) || empty($receivable_id)) {
            return $this->error('参数错误');
        }
        $userAccount = $this->getUserAccountByUerID($user_id);
        if (empty($userAccount['data'])) {
            return $this->error('获取用户账号基本信息错误');
        }
        //获取当前总余额
        $balance = $userAccount['data']['balance'];
        $t = time();
        //插入充值流水表--充值账单,只有账单审核通过后，账号可用余额财务增加本次充值的金额
        $result_recharge = $this->insertUserAccountRecharge($user_id, $amount, $type, $balance, $receivable_id, $vip_lv);
        if (!empty($result_recharge['data'])) {
            //充值业务101是要记录收入，但是如果是VIP开通，则不计入收入
            if ($business_type != 101 && $vip_lv > 0) {
                //插入收入流水表
                $result_income = $this->insertUserAccountIncome($user_id, $amount, $business_type, $result_recharge['data']);
                if (!empty($result_income['data'])) {
                    return $this->success('成功', $result_income);
                } else {
                    return $this->error('插入收入流水表失败');
                }
            } else {
                return $this->success('成功', $result_recharge['data']);
            }
        } else {
            return $this->error('插入充值流水失败');
        }
    }

    /**
     * 插入用户充值信息
     * @param int $user_id 用户ID
     * @param string $amount 本次充值金额
     * @param int $recharge_type 充值渠道类型，101 银行卡，201 微信，301 支付宝
     * @param string $before_balance 充值前金额
     * @param int $receivable_id 平台收款的信息ID
     * @param int $vip_lv VIP 级别
     * @return array
     */
    public function insertUserAccountRecharge(int $user_id,string $amount,int $recharge_type,string $before_balance,int $receivable_id,int $vip_lv) : array
    {
        if (empty($user_id) || empty($receivable_id)) {
            return $this->error('参数错误');
        }
        if (empty($amount) || $amount < 0 || $amount > 100000) {
            return $this->error('充值金额错误');
        }
        //检查一下传入的平台收款卡的ID是否正确
        $check  = $this -> getReceivableByID($receivable_id);
        if($check['status'] == 0){
            return $this->error('充值失败，平台收款信息错误');
        }
        $userModel = new ModelUserAccountRechange();
        $t = time();
        //充值流水号
        $recharge_number = $t . '-' . $user_id .'-' . rand(0,10000);
        $data = [
            'user_id' => $user_id,
            'receivable_id' => $receivable_id,
            'recharge_number' => $recharge_number,
            'recharge_profit' => $amount,
            'recharge_type' => $recharge_type,
            'before_balance' => $before_balance,
            'current_balance' => ($before_balance + $amount),
            'status' => 1, //是否审核, 1 未审核，2 已审核,默认1
            'vip_lv' => $vip_lv,
            'create_time' => $t,
            'payment_status' => 1, //充值状态: 1 待付款, 2 已付款;3 取消; 默认：1 待付款
            'expiration_time' => $t + 3000 // 50分钟后过期，50分钟=3000秒
        ];
        $result = $userModel->insertGetId($data);
        return $this->success('成功', $result);
    }

    /**
     * 获取支付订单的详情--根据支付单ID
     * @param int $user_id 用户ID
     * @param int $order_id 订单ID
     * @return array
     */
    public function getRechargeOrderById(int $user_id,int $order_id) : array
    {
        if (empty($user_id) || empty($order_id)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserAccountRechange();
        $where =[
            'id' => $order_id,
            'user_id' => $user_id
        ];
        $result = $userModel->where($where)->findOrEmpty()->toArray();
        //dump($userModel-> getLastSql());die();
        return $this->success('成功', $result);
    }

    /**
     * 获取用户自己的充值记录--支持动态分页
     * @param int $user_id 当前用户ID
     * @param int $page 获取第几页的数据
     * @param int $size 分页尺寸;只支持，5,10,20分页尺寸
     * @return array 返回推荐任务的数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getRechargeOrderListByUserId(int $user_id,int $page, int $size = 10): array
    {
        if(empty($user_id)){
            return $this -> error('用户ID必传');
        }
        $currentStart  = 0 ;
        $currentEnd  = 0 ;
        if ($size < 10) {
            $size = 10;
        }
        if($size != 10 && $size != 20 && $size != 5){
            $size = 10;
        }
        if ($page <= 0) {
            $page = 0;
            $currentEnd  = $size ;
        }else{
            if($page > 50){
                $page = 50;
            }
            $currentStart  = $page * $size;
            $currentEnd  = $currentStart + $size;
        }
        /*
        $list = Db::query("select *
from user_account_recharge t
where t.user_id = ?
     limit ?,?", [$user_id,$currentStart,$currentEnd]);
*/
        $userModel = new ModelUserAccountRechange();
        $list = $userModel -> where('user_id',$user_id)
            ->field('id,user_id,recharge_number as number,create_time,recharge_profit,status,payment_status,remark')
            ->page($page,$size)
            -> select();
        //dump($page,$size,$userModel -> getLastSql());die();
        if(empty($list)){
            return $this->error('暂无充值记录');
        }else{
            foreach ($list as &$value){
                if(!empty($value['status'])){
                    $status = '';
                    //是否审核, 1 未审核，2 已审核-通过 , 3 审核不通过;,默认1
                    switch($value['status']){
                        case '1':
                            $status = '未审核';
                            break;
                        case '2':
                            $status = '已审核';
                            break;
                        case '3':
                            $status = '审核不通过';
                            break;
                        default:
                            $status = '未知';
                            break;
                    }
                    $value['status'] = $status;
                }
                if(!empty($value['payment_status'])){
                    //充值状态: 1 待付款, 2 已付款;3 取消; 默认：1 待付款
                    $payment_status = '';
                    switch($value['payment_status']){
                        case '1':
                            $payment_status = '待付款';
                            break;
                        case '2':
                            $payment_status = '已付款';
                            break;
                        case '3':
                            $payment_status = '已取消';
                            break;
                        default:
                            $payment_status = '未知';
                            break;
                    }
                    $value['payment_status'] = $payment_status;
                }
            }
            return $this->success('成功', $list);
        }
    }


    /**
     * @param int $user_id 用户ID
     * @param string $amount 本次充值金额
     * @param int $type 任务收益类型: 101:充值；201:任务；301:推广；401:团队
     * @param int $recharge_id 业务类型数据的表的ID，例如：充值成功的业务ID
     * @return array
     */
    public function insertUserAccountIncome(int $user_id,string $amount,int $type,int $recharge_id) : array
    {
        if (empty($user_id) || empty($type) || empty($recharge_id) || empty($amount)) {
            return $this->error('参数错误');
        }
        if ($amount < 0 || $amount > 100000) {
            return $this->error('充值金额错误');
        }
        $userModel = new ModelUserAccountIncome();
        $field_name = '';
        switch ($type) {
            case 101:
                $field_name = 'account_recharge_id';
            case 201:
                $field_name = 'account_task_complete_id';
            case 301:
                $field_name = 'account_popularize_id';
            case 401:
                $field_name = 'account_team_id';
            default:
                $field_name = 'account_recharge_id';
        }
        $data = [
            'user_id' => $user_id,
            'account_profit' => $amount,
            $field_name => $recharge_id,
            'profit_type' => $type,
            'income_time_day' => date('Ymd'),
            'create_time' => time()
        ];
        $result = $userModel->insertGetId($data);
        return $this->success('成功', $result);
    }

    /**
     * 后台审核用户充值信息方法--通用方法
     * @param int $user_id 用户ID
     * @param int $check_Info_id 被审查的信息ID
     * @param int $checkValue 审核值，2 审核通过，3 审核不通过
     * @param int $check_user_id 审核信息用户ID
     * @param string $tableName 表名字，必要字段
     * @return array
     */
    public function checkUerRecharge(int $user_id,int $check_Info_id,int $checkValue,int $check_user_id,string $tableName) : array
    {
        if (empty($user_id) || empty($check_Info_id) || empty($checkValue) || empty($check_user_id) || empty($tableName)) {
            return $this->error('参数错误');
        }
        $info = $this->getUserRechargeByID($check_Info_id);
        if (empty($info['data'])) {
            return $this->error('要操作的信息不存在');
        }
        //判断信息是否审核过了
        if($info['data']['status'] != 1){
            return $this->error('信息不可重复审核',$check_Info_id);
        }
        //2  审核通过，3 审核不通过
        if ($checkValue != 2 && $checkValue != 3) {
            return $this->error('审核状态:'.$checkValue.'只能是2 通过，3 驳回');
        }
        $modelUser = new ModelUserAccountRechange();
        $where = [
            'user_id' => $user_id,
            'id' => $check_Info_id,
            'payment_status' => 2 //充值状态: 1 待付款, 2 已付款;3 取消; 默认：1 待付款
        ];
        $t = time();
        $data = [
            'status' => $checkValue,
            'update_time' => $t,
            'update_user_id' => $check_user_id,
            'remark' => '审核：'.$checkValue == 3 ? "驳回" : '通过，传入的值checkValue：'.$checkValue,
        ];
        //dump($where,$data); die();
        $result = $modelUser->where($where)->save($data);
        if ($result) {
            //驳回：审核不通过则直接返回了
            if($checkValue == 3){
                return $this->success('审核操作成功',1);
            }
            $user_id = $info['data']['user_id'];
            $receivable_id = $info['data']['receivable_id'];
            $amount = $info['data']['recharge_profit'];
            $vip_lv = $info['data']['vip_lv'];
            //$recharge_type = $info['data']['recharge_type'];
            $result = Db::name('user_account')
                ->where('user_id', $user_id)
                ->update([
                    'balance' => Db::raw('balance +' . $amount), //增加充值额度
                    //'frozen_balance' => Db::raw('frozen_balance - ' . $amount),
                    'update_time' => $t
                ]);
            if ($result > 0) {
                //增加收入流水表
                $result_income = $this->insertUserAccountIncome($user_id, $amount, 101, $receivable_id);
                if (!empty($result_income['data'])) {
                    //如果是$vip_lv > 0,代表是要升级VIP
                    if ($vip_lv > 0 ) {
                        $userService = new UserService();
                        $u_info = $userService -> getUserInfoById($user_id);
                        if($u_info['status'] == 0) {
                            return $this->error('未查询到当前充值用户信息');
                        }
                        //充值前的用户VIP级别，如果是=0且当前$vip_lv> 0 则说明是首次开通VIP，则就需要触发推广收益
                        $u_info_vip_lv = $u_info['data']['vip_lv'];
                        //更新用户VIP级别
                        $r = $userService->updateUserStatusByID($user_id, $vip_lv,0,$amount);
                        if ($r['status'] == 0) {
                            return $this->error('审核成功,插入收入流水表成功但是用户账号VIP更新-失败');
                        } else {
                            //VIP更新成功后，给推荐人分成--推广收益TODO
                            //直接上级收益充值金额的15%--当前用户开通的级别要等于推荐人级别，高于部分不算
                            //直接上级的上级获得5%;
                            //直接上级的上级的上级获得3%;
                            if($u_info_vip_lv > 0){
                                //计算推广用户收益 Calculate promotion user revenue
                                $r = $this -> calculatePromotionUserRevenue($user_id,$amount,$vip_lv);
                                if($r['status'] == 1){
                                    return $this->success('审核成功,插入收入流水表成功且用户账号VIP更新,且是首次升级VIP触发层级收益-成功',$r['data']);
                                }else{
                                    return $this->success('审核最终失败，未回滚,插入收入流水表成功且用户账号VIP更新-成功，但是因为首次升级VIP触发层级收益-失败,消息：'.$r['msg'],$r['data']);
                                }
                            }else{
                                return $this->success('审核成功,插入收入流水表成功且用户账号VIP更新-成功',1);
                            }
                        }
                    }else{
                        return $this->success('审核成功,插入收入流水表成功', $result_income);
                    }
                } else {
                    return $this->error('插入收入流水表失败');
                }
            } else {
                return $this->error('用户账号更新失败');
            }
        }else {
            return $this->error('审核失败--更新充值单数据状态失败');
        }
    }

    /**
     * 计算推广用户收益 Calculate promotion user revenue
     * VIP更新成功后，给推荐人分成--推广收益TODO
            直接上级收益充值金额的15%--当前用户开通的级别要等于推荐人级别，高于部分不算
            直接上级的上级获得5%;
            直接上级的上级的上级获得3%;
     * @param int $user_id
     * @param string $amount
     * @param int $currentUserVip
     * @return array
     */
    public function calculatePromotionUserRevenue(int $user_id,string $amount,int $currentUserVip) : array
    {
        if (empty($user_id) || empty($amount) || empty($currentUserVip)) {
            return $this->error('参数错误');
        }
        $userService = new UserService();
        $currentUser = $userService -> getUserInfoById($user_id);
        if($currentUser['status'] == 1 && !empty($currentUser['data'])) {
            if ($currentUser['data']['lv'] == 4) {
                return $this->error('四级用户没有收益');
            }
            /**
            //从一级往下算吧
            //一级子，收益15%
            if($currentUser['data']['lv'] == 1){
                  $parentUser = $userService -> getUserInfoById($currentUser['data']['pid']);
                if($parentUser['status'] == 1 && !empty($parentUser['data'])) {
                    $user_id = $parentUser['data']['id'];
                    //增加用户收益;  插入income
                    $parent_income = $amount * 0.15;
                    //更新用户账号收入
                    $u = $userAccountService ->addUserAccountBalance($user_id, $parent_income);
                    if ($u['status'] == 0) {
                        return $this->error('更新用户账号失败');
                    } else {
                        //插入 user_account_popularize 推广收益流水
                        $data = [
                            'user_id' => $user_id, //推荐人信息
                            'user_vip_lv' => $parentUser['data']['vip_lv'],
                            'user_lv' => $parentUser['data']['lv'],
                            'popularize_user_id' => $currentUser['data']['id'],
                            'popularize_user_vip_lv' => $currentUser['data']['vip_lv'],
                            'popularize_user_lv' => $currentUser['data']['lv'],
                            'popularize_profit' => $parent_income,
                        ];
                        $result = $this -> insertUserAccountPopularize($data);
                        if($result['status'] == 1){
                            $info_id = $result['data'];
                            //插入用户收入表
                            $i = $this->insertUserAccountIncome($user_id, $parent_income, 301, $info_id);
                            return $this->success('收益分配成功', 1);
                        }else{
                            return $this->error('流水插入失败');
                        }
                    }
                }else{
                    return $this->error('一级父类查询失败');
                }
            }elseif($currentUser['data']['lv'] == 2){
                //给直接父级分配利润和父级的上级分配
                //直接父级分配利润15%

                //父级的上级分配利润5%

            }
            */
            $current_lv_path = $currentUser['data']['lv_path'];
            $ids = str_replace("-",",",$current_lv_path);
            //$ids = explode("-",$current_lv_path);
            $last= strripos($ids,',');
            //var_dump($ids,$last,strlen($ids));die();
            if($last == strlen($ids) - 1 ){
                $ids = substr($ids, 0, -1);
            }
            //通过当前用户
            $parent_users = $userService->getUserListByIds($ids);
            if ($parent_users['status'] == 1 && !empty($parent_users['data'])) {
                $result = 0;
                $parent_user1 = []; //一级用户数据缓存
                $parent_user2 = []; //二级用户数据缓存
                $count = count($parent_users['data']);

                $parent_user_temp = []; //当用户是2级时特殊变量，存储一下一级用户数据
                foreach ($parent_users['data'] as $key => $value) {
                    //直接一级用户收益
                    if ($count == 1) {
                        $shouyilv = 0.15;
                        $usedVip = 0;
                        //父级比子级级别低，则取低级别的
                        //2级的子级是当前用户
                        if ($value['vip_lv'] <= $currentUserVip) {
                            $usedVip = $value['vip_lv'];
                        }
                        $fee = 0;
                        $paymentService = new PaymentService();
                        $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                        $income = $fee * $shouyilv;
                        $r2 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $currentUser['data']);
                        $result = 1;
                        //dump($result,$value['id'],$income);
                    } elseif ($count == 2) { //说明是有徒孙和徒弟两个级别
                        if ($value['lv'] == 1) {
                            $shouyilv = 0.15;
                            $usedVip = 0;
                            //父级比子级级别低，则取低级别的
                            //2级的子级是当前用户
                            if ($value['vip_lv'] <= $currentUserVip) {
                                $usedVip = $value['vip_lv'];
                            }
                            $fee = 0;
                            $paymentService = new PaymentService();
                            $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                            $income = $fee * $shouyilv;
                            $r2 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $currentUser['data']);
                            $result = 21;
                            $parent_user_temp = $value;
                            //dump($result,$value['id'],$income);
                        } elseif ($value['lv'] == 0) {
                            $shouyilv = 0.05;
                            $usedVip = 0;
                            //父级比子级级别低，则取低级别的
                            //2级的子级是当前用户
                            if ($parent_user_temp['vip_lv'] <= $currentUserVip) {
                                $usedVip = $value['vip_lv'];
                            }
                            if ($usedVip >= $value['vip_lv']) {
                                $usedVip = $value['vip_lv'];
                            }
                            $fee = 0;
                            $paymentService = new PaymentService();
                            $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                            $income = $fee * $shouyilv;
                            $r2 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $parent_user_temp);
                            $result = 20;
                            //dump($result,$value['id'],$income);
                        }
                    } else {
                        //这里正常情况是$count = 3 正常的三级分销都是三级
                        if ($value['lv'] == 2) {
                            $shouyilv = 0.15;
                            $usedVip = 0;
                            //父级比子级级别低，则取低级别的
                            //2级的子级是当前用户
                            if ($value['vip_lv'] <= $currentUserVip) {
                                $usedVip = $value['vip_lv'];
                            }
                            $fee = 0;
                            $paymentService = new PaymentService();
                            $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                            $income = $fee * $shouyilv;
                            //var_dump($value);die();
                            $r2 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $currentUser['data']);
                            $result = 12;
                            $parent_user2 = $value;
                            //dump($result,$value['id'],$income);
                        } elseif ($value['lv'] == 1) {
                            $shouyilv = 0.05;
                            $usedVip = 0;
                            //父级比子级级别低，则取低级别的
                            //上级父级的子级是父级
                            if ($parent_user2['vip_lv'] <= $currentUserVip) {
                                $usedVip = $parent_user2['vip_lv'];
                            }
                            if ($usedVip >= $value['vip_lv']) {
                                $usedVip = $value['vip_lv'];
                            }
                            $fee = 0;
                            $paymentService = new PaymentService();
                            $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                            $income = $fee * $shouyilv;
                            $r1 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $parent_user2);
                            $parent_user1 = $value;
                            $result = 11;
                            //dump($result,$value['id'],$income);
                        } elseif ($value['lv'] == 0) {
                            $shouyilv = 0.03;
                            $usedVip = 0;
                            //父级比子级级别低，则取低级别的
                            //上级父级的子级是父级
                            if ($parent_user2['vip_lv'] <= $currentUserVip) {
                                $usedVip = $parent_user2['vip_lv'];
                            }
                            if ($usedVip >= $parent_user1['vip_lv']) {
                                $usedVip = $parent_user1['vip_lv'];
                            }
                            if ($usedVip >= $value['vip_lv']) {
                                $usedVip = $value['vip_lv'];
                            }
                            $fee = 0;
                            $paymentService = new PaymentService();
                            $fee = $paymentService->getVipFeeByVipLv($usedVip)['data'];
                            $income = $fee * $shouyilv;
                            $r0 = $this->addUserBalanceForPopularize($value['id'], $income, $value, $parent_user1);
                            $result = 10;
                            //dump($result,$value['id'],$income);
                        }
                    }
                }
                if ($result > 0) {
                    return $this->success('恭喜,收益分配成功', $result);
                }
            } else {
                return $this->error('父级用户没查到');
            }
        }else{
            return $this->error('用户信息没查到');
        }
    }

    /**
     * 添加用户账号可用余额--推广收益（301）
     * @param int $user_id 用户id
     * @param string $income 收益
     * @param array $parentUser 父级用户数据
     * @param array $currentUser 长期级别用户数据
     * @return array
     */
    public function addUserBalanceForPopularize(int $user_id,string $income,array $parentUser,array $currentUser){
        //$user_id = $parentUser['data']['id'];
        //增加用户收益;  插入income
        $parent_income = $income;
        $userAccountService =  new UserAccountService();
        //更新用户账号收入
        $u = $userAccountService ->addUserAccountBalance($user_id, $parent_income,301);
        //var_dump($u);die();
        if ($u['status'] == 0) {
            return $this->error('更新用户账号失败');
        } else {
            //插入 user_account_popularize 推广收益流水
            $data = [
                'user_id' => $user_id, //推荐人信息
                'user_vip_lv' => $parentUser['vip_lv'],
                'user_lv' => $parentUser['lv'],
                'popularize_user_id' => $currentUser['id'],
                'popularize_user_vip_lv' => $currentUser['vip_lv'],
                'popularize_user_lv' => $currentUser['lv'],
                'popularize_profit' => $parent_income,
            ];
            $result = $this -> insertUserAccountPopularize($data);
            //var_dump($result);
            if($result['status'] == 1){
                $info_id = $result['data'];
                //插入用户收入表
                $i = $this->insertUserAccountIncome($user_id, $parent_income, 301, $info_id);
                return $this->success('收益分配成功', 1);
            }else{
                return $this->error('流水插入失败');
            }
        }
    }


    /**
     * 根据信息ID获取用户充值信息
     * @param int $id 信息ID
     * @param string $field 返回的字段，默认*
     * @return array
     */
    public function getUserRechargeByID(int $id,string $field='*') : array
    {
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserAccountRechange();
        $result = $userModel->where('id', $id)
            ->field($field)
            ->findOrEmpty()
            ->toArray();
        return $this->success('成功', $result);
    }

    /**
     * 根据ID获取平台收款卡信息
     * @param int $id 信息ID
     * @param string $field 返回的字段，默认*
     * @return array
     */
    public function getReceivableByID(int $id,string $field='*') : array
    {
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelReceivable();
        $result = $userModel->where('id', $id)
            ->field($field)
            ->findOrEmpty()
            ->toArray();
        //dump($userModel->getLastSql());die();
        return $this->success('成功', $result);
    }

    /**
     * @param int $user_id
     * @param int $order_id 支付订单的表ID
     * @param string $ping_zheng_pic_url 付款凭证图片地址，多个用;拼接
     * @param string $remark 用户备注，可空
     * @return array
     */
    public function commitRechargeOrder(int $user_id,int $order_id,string $ping_zheng_pic_url,string $remark) : array
    {
        if (empty($user_id) || empty($order_id) || empty($ping_zheng_pic_url)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserAccountRechange();
        $where = [
            ['user_id','=', $user_id],
            ['id' ,'=', $order_id],
            ['expiration_time','<=' , time() ] //超时不给支付
        ];
        $result = $userModel->where($where)
            ->update([
                'ping_zheng_pic_url' => $ping_zheng_pic_url,
                //'remark' => Db::raw('remark + ' . $remark), //todo
                'remark' => $remark,
                'payment_status' => 2,//充值状态: 1 待付款, 2 已付款;3 取消; 默认：1 待付款
            ]);
        return $this->success('成功', $result);
    }

    /**
     * @param int $user_id
     * @param int $order_id 支付订单的表ID
     * @param string $remark 取消原因，非必填
     * @return array
     */
    public function cancelMyOrderRechargeOrder(int $user_id,int $order_id,string $remark) : array
    {
        if (empty($user_id) || empty($order_id)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserAccountRechange();
        $where = [
            ['user_id','=', $user_id],
            ['id' ,'=', $order_id],
            ['payment_status' ,'=', 1] //只有待付款的才可以取消
        ];
        $result = $userModel->where($where)
            ->update([
                'payment_status' => 3,//充值状态: 1 待付款, 2 已付款;3 取消; 默认：1 待付款
                'update_time' => time(),
                'remark' => '取消订单原因:'.$remark
                ]);
        return $this->success('成功', $result);
    }

    /**
     * 用户提现/购买VIP消费用账号余额
     * @param int $user_id 用户ID
     * @param string $amount 本次消费金额
     * @param int $cost_type 消费类型:1 提现; 2 通过账号可用余额购买VIP;
     * @param int $card_id 平台收款的信息ID(近提现时用，如果是充值VIP则等于0)
     * @param int $vip_lv VIP 级别
     * @return array
     */
        public function insertUserAccountCost(int $user_id,string $amount,int $cost_type,int $card_id,int $vip_lv=0) : array
        {
            if (empty($user_id) || empty($cost_type)) {
                return $this->error('参数错误');
            }
            //1 提现支出; 2 通过账号可用余额购买VIP--支出;
            if ($cost_type != 1 && $cost_type != 2) {
                return $this->error('参数错误--业务类型错误');
            }
            if (empty($card_id) && empty($vip_lv)) {  //当用
                return $this->error('参数错误--用户提现/购买VIP关键信息不可同时为空');
            }
            if (empty($amount) || $amount < 0 || $amount > 100000) {
                return $this->error('本次消费金额错误');
            }
            $my_card_type = '';
            if($cost_type ==1){
                if (!empty($card_id)) {
                    $check = $this->getUserCardInfoById($user_id, $card_id);
                    if ($check['status'] == 0) {
                        return $this->error($check['msg']);
                    }
                    $my_card_type = $check['data']['income_account_type']; //收款码类型，101 银行卡,201 微信，301 支付宝
                }
            }elseif ($cost_type ==2){
                $my_card_type = '通过账号可用余额购买VIP--支出,不需要输入用户收款的卡片信息';
            }
            $userModel = new ModelUserAccountCost();
            $t = time();
            //流水号
            $number = $t . '-' . $user_id . '-' . rand(0, 10000);
            $data = [
                'user_id' => $user_id,
                'my_card_id' => $card_id,
                'my_card_type' => $my_card_type,
                'number' => $number,
                'amount' => $amount,
                'cost_type' => $cost_type,
                'vip_lv' => $vip_lv,
                'create_time' => $t,
                'create_time_day' => date('Ymd'),
                'remark' => '',
                'status' => 1 //提现申请的状态: 1 待审核; 2 驳回; 3 待付款; 4 已付款;
            ];
            if ($cost_type == 2) { //使用余额购买VIP
                //扣余额成功后，修改用户VIP等级，然后记录VIP日志
                $result = Db::name('user_account')
                    ->where('user_id', $user_id)
                    ->update([
                        'balance' => Db::raw('balance +' . $amount), //增加充值额度
                        'recharge_profit' => Db::raw('recharge_profit + ' . $amount),
                        'update_time' => $t
                    ]);
                if ($result > 0) {
                    $userService = new UserService();
                    //更新用户VIP级别
                    $r = $userService->updateUserStatusByID($user_id, $vip_lv, 0, $amount);
                    if ($r['status'] == 0) {
                        return $this->error('用户账号更新失败');
                    } else {
                        //不用审核了，自动到账，自动升级
                        $data['vip_lv'] = $vip_lv;
                        $data['status'] = 4;
                        $data['remark'] = '用户余额升级VIP，自动到账，自动升级';
                        $result = $userModel->insertGetId($data);
                        return $this->success('用户余额升级VIP，自动到账，自动升级成功', $result);
                    }
                } else {
                    return $this->error('用户账号更新失败');
                }
            } else {
                $result = $userModel->insertGetId($data);
                return $this->success('提现申请成功', $result);
            }
        }

    /**
     * @param int $user_id
     * @param string $income_account 收款账号
     * @param string $account_name  收款账号名称，如果是银行卡则填写户主
     * @param string $income_account_code_url 收款码图片地址
     * @param string $income_account_type 收款码类型，101 银行卡,201 微信，301 支付宝
     * @param string $income_account_bank_name 收款银行名称
     * @param string $income_account_bank_account_name 银行开户行名称
     * @param int $is_default 是否默认； 1 默认，0 非默认
     * @return array
     */
    public function insertUserAccountCard(int $user_id,string $income_account,string $account_name,string $income_account_code_url
        ,string $income_account_type,string $income_account_bank_name,string $income_account_bank_account_name,int $is_default=1) : array
    {
        if (empty($user_id) || empty($income_account) || empty($account_name) || empty($income_account_type)) {
            return $this->error('参数错误');
        }
        if ($is_default != 1 && $is_default != 0) {
            return $this->error('参数错误--是否默认值错误');
        }
        $check = $this -> getUserCardByAccount($income_account,$income_account_type);
        if($check['status'] == 1){
            return $this->error('收款账号重复，请核实');
        }
        $userModel = new ModelUserAccountCard();
        if($is_default == 1){
            $c_where  = [
              'user_id' =>   $user_id,
                'is_default' => $is_default,
            ];
             $r = $userModel -> where($c_where) -> count();
             if($r > 0){
                 //把之前的默认的卡设置为非默认
                 $s = $userModel -> where($c_where) -> save(['is_default' => 0]);
             }
        }
        $data = [
            'user_id' => $user_id,
            'income_account_type' => $income_account_type,
            'income_account' => $income_account,
            'income_account_name' => $account_name,
            'income_account_code_url' => $income_account_code_url,
            'income_account_bank_name' => $income_account_bank_name,
            'income_account_bank_account_name' => $income_account_bank_account_name,
            'is_default' => $is_default,
            'is_delete' => 0,
            'create_time' => time()
        ];

        $result = $userModel->insertGetId($data);
        if ($result) {
            return $this->success('成功', $result);
        } else {
            return $this->error('更新用户数据失败');
        }
    }

    /**
     * 用户完成任务后收益信息
     * @param int $user_id 用户ID
     * @param int $task_id 任务ID
     * @param int $user_task_id 用户任务ID
     * @param string $amount 收益
     * @return array
     */
    public function insertUserAccountTaskComplete(int $user_id,int $task_id,int $user_task_id,string $amount) : array
    {
        if (empty($user_id) || empty($task_id) || empty($user_task_id) || empty($amount)) {
            return $this->error('参数错误');
        }
        $userCompleteModel = new ModelUserAccountTaskComplete();
        $data = [
            'task_id' => $task_id,
            'user_id' => $user_id,
            'user_task_id' => $user_task_id,
            'task_profit' => $amount,
            'create_time' => time(),
        ];
        $result = $userCompleteModel->insertGetId($data);
        if ($result) {
            return $this->success('成功', $result);
        } else {
            return $this->error('更新用户数据失败');
        }
    }


    /**
     * 插入用户推广收益表流水数据
     * @param array $data 用户ID
     * @return array
     */
    public function insertUserAccountPopularize(array $data) : array
    {
        if (empty($data)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserAccountPopularize();
        $data = [
            'user_id' => $data['user_id'],
            'user_vip_lv' => $data['user_vip_lv'],
            'user_lv' => $data['user_lv'],
            'popularize_user_id' => $data['popularize_user_id'],
            'popularize_user_vip_lv' => $data['popularize_user_vip_lv'],
            'popularize_user_lv' => $data['popularize_user_lv'],
            'popularize_profit' => $data['popularize_profit'],
            'create_time' => time(),
        ];
        $result = $userModel->insertGetId($data);
        if ($result) {
            return $this->success('成功', $result);
        } else {
            return $this->error('更新用户数据失败');
        }
    }


    /**
     * 当用户提现时，获取用户的默认的收款的卡片信息（银行卡，微信，支付宝）
     * @param int $user_id 用户ID
     * @return array
     */
    public function getUserReceiveDefaultCardInfo(int $user_id):array{
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        $modelUserCard = new ModelUserAccountCard();
        $where = [
          'user_id' => $user_id,
          'is_default' => 1,
            'is_delete' => 0
        ];
        $result = $modelUserCard -> where($where) -> findOrEmpty() -> toArray();
        //dump($modelUserCard -> getLastSql()); die();
        return $this -> success('成功',$result);
    }

    /**
     * 获取用户自己的充值记录--支持动态分页
     * @param int $user_id 当前用户ID
     * @param int $page 获取第几页的数据
     * @param int $size 分页尺寸;只支持，5,10,20分页尺寸
     * @return array 返回推荐任务的数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserAccountCardList(int $user_id,int $page, int $size = 10): array
    {
        if(empty($user_id)){
            return $this -> error('用户ID必传');
        }
        if ($size < 10) {
            $size = 10;
        }
        if($size != 10 && $size != 20 && $size != 5){
            $size = 10;
        }
        if ($page <= 0) {
            $page = 0;
        }else{
            if($page > 50){
                $page = 50;
            }
        }
        $userModel = new ModelUserAccountCard();
        $list = $userModel -> where('user_id',$user_id)
            -> where('is_delete',0)
            ->field('*')
            ->page($page,$size)
            -> select();
        //dump($page,$size,$userModel -> getLastSql());die();
        return $this->success('成功', $list);
    }

    /**
     * 当用户提现时，获取用户的默认的收款的卡片信息（银行卡，微信，支付宝）
     * @param int $user_id 用户ID
     * @param int $id  信息ID
     * @return array
     */
    public function getUserCardInfoById(int $user_id,int $id):array{
        if (empty($user_id) || empty($id)) {
            return $this->error('参数错误');
        }
        $modelUserCard = new ModelUserAccountCard();
        $where = [
            'user_id' => $user_id,
            'id' => $id,
            'is_delete' => 0 //是否删除标识;默认0 未删除，1 删除
        ];
        $result = $modelUserCard -> where($where) -> findOrEmpty() -> toArray();
        return $this -> success('成功',$result);
    }

    /**
     * 删除用户收款信息--某个卡片
     * @param int $user_id 用户ID
     * @param int $id  信息ID
     * @return array
     */
    public function deleteUserCardInfoById(int $user_id,int $id):array{
        if (empty($user_id) || empty($id)) {
            return $this->error('参数错误');
        }
        $modelUserCard = new ModelUserAccountCard();
        $where = [
            'user_id' => $user_id,
            'id' => $id,
            'is_delete' => 0 //是否删除标识;默认0 未删除，1 删除
        ];
        $data = [
            'is_delete' => 1, //是否删除标识;默认0 未删除，1 删除
            'update_time' => time(),
        ];
        $result = $modelUserCard -> where($where) -> save($data);
        if(!empty($result)){
            return $this -> success('成功',$result);
        }else{
            return $this -> error('删除失败');
        }
    }

    /**
     * 编辑用户收款基本信息--某个卡片
     * @param int $user_id 用户ID
     * @param int $id 信息ID
     * @param string $income_account 收款账号
     * @param string $account_name  收款账号名称，如果是银行卡则填写户主
     * @param string $income_account_code_url 收款码图片地址
     * @param string $income_account_type 收款码类型，101 银行卡,201 微信，301 支付宝
     * @param string $income_account_bank_name 收款银行名称
     * @param string $income_account_bank_account_name 银行开户行名称
     * @param int $is_default 是否默认； 1 默认，0 非默认
     * @return array
     */
    public function editUserCardInfoById(int $user_id,int $id,string $income_account,string $account_name,string $income_account_code_url
        ,string $income_account_type,string $income_account_bank_name,string $income_account_bank_account_name,int $is_default=1) : array
    {
        if (empty($user_id) || empty($id) || empty($income_account) || empty($account_name) || empty($income_account_type)) {
            return $this->error('参数错误');
        }
        if ($is_default != 1 && $is_default != 0) {
            return $this->error('参数错误--是否默认值错误');
        }
        $userModel = new ModelUserAccountCard();
        if ($is_default == 1) {
            $c_where = [
                'user_id' => $user_id,
                'is_default' => $is_default,
                'is_delete' => 0
            ];
            $r = $userModel->where($c_where)->findOrEmpty();
            if (!empty($r)) {
                if ($r['id'] <> $id) {
                    $s = $userModel->where($c_where)->save(['is_default' => 0]);
                }
            }
        }
        $check = $this->getUserCardByAccount($income_account, $income_account_type);
        if ($check['status'] == 1) {
            if($check['data']['id']  != $id){
                return $this->error('收款账号重复，请核实');
            }
        }
        $where = [
            'user_id' => $user_id,
            'id' => $id,
            'is_delete' => 0,
        ];
        $data = [
            'income_account_type' => $income_account_type,
            'income_account' => $income_account,
            'income_account_name' => $account_name,
            'income_account_code_url' => $income_account_code_url,
            'income_account_bank_name' => $income_account_bank_name,
            'income_account_bank_account_name' => $income_account_bank_account_name,
            'is_default' => $is_default,
            'update_time' => time()
        ];
        //如果没修改图片，就用原来图片更新
        if(empty($income_account_code_url)){
           unset($data['income_account_code_url']); //如果没修改图片，则地址字段不动
        }
        $result = $userModel->where($where)->save($data);
        if ($result) {
            return $this->success('成功', $result);
        } else {
            return $this->error('更新用户数据失败');
        }
    }

    /**
     * 当用户提现时，获取用户的默认的收款的卡片信息（银行卡，微信，支付宝）
     * @param string $account  收款账号；全表唯一，不可为空
     * @param string $account_type 收款码类型，101 银行卡,201 微信，301 支付宝
     * @return array
     */
    public function getUserCardByAccount(string $account,string $account_type):array{
        if (empty($account) || empty($account_type)) {
            return $this->error('参数错误');
        }
        $modelUserCard = new ModelUserAccountCard();
        $where = [
            'income_account' => $account,
            'income_account_type' => $account_type,
            //'is_delete' => 0, 全表检查，不要加这个条件
        ];
        $result = $modelUserCard -> where($where) -> findOrEmpty() -> toArray();
        return $this -> success('成功',$result);
    }

    /**
     * 获取某个提现信息的具体信息--通过信息ID
     * @param int $id  信息ID
     * @return array
     */
    public function getUserAccountCostById(int $id):array{
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $modelUserCost = new ModelUserAccountCost();
        $where = [
            //'user_id' => $user_id,
            'id' => $id,
        ];
        $result = $modelUserCost -> where($where) -> findOrEmpty() -> toArray();
        return $this -> success('成功',$result);
    }

    /**
     * 后台系统审核用户提现申请的方法（支持支付完成状态更新）
     * @param int $user_id 用户ID
     * @param int $check_Info_id  信息ID
     * @param int $checkValue 审核值，提现申请的状态: 1 待审核; 2 驳回; 3 待付款; 4 已付款;
     *           所以驳回传入：2 通过插入3； 等最终完成付款后，改成已付款;
     * @param int $check_user_id 审核人ID
     * @param string $remark 备注，非必填
     * @return array
     */
    public function checkUserAccountCostById(int $user_id,int $check_Info_id,int $checkValue,int $check_user_id,string $remark) : array
    {
        if (empty($user_id) || empty($check_Info_id) || empty($checkValue) || empty($check_user_id)) {
            return $this->error('参数错误');
        }
        $whereStatus = 1;
        if ($checkValue == 4) { //当后台业务付款后，需要确认付款，那状态就是4，所以要去更新的数据的状态是3（待付款）
            $whereStatus = 3;
        }
        $modelUserCost = new ModelUserAccountCost();
        $where = [
            'user_id' => $user_id,
            'id' => $check_Info_id,
            'status' => $whereStatus
        ];
        $data = [
            'status' => $checkValue,
            'update_user_id' => $check_user_id,
            'update_time' => time(),
            'remark' => $remark,
        ];
        $result = $modelUserCost->where($where)->save($data);
        if ($result) {
            //后台已付款
            //已付款，账号可用余额扣减
            if ($checkValue == 4) {
                $userCost = $this -> getUserAccountCostById($check_Info_id);
                if($userCost['status'] == 1 && !empty($userCost['data'])){
                    $amount = $userCost['data']['amount'];
                    $t = time();
                    $whereSql = [
                                     [ 'user_id','=', $user_id],
                                     ['balance','>',$amount],
                               ];
                    //扣余额
                    $result = Db::name('user_account')
                        ->where($whereSql)
                        ->update([
                            'balance' => Db::raw('balance -' . $amount), //扣余额
                            //'recharge_profit' => Db::raw('recharge_profit - ' . $amount), //累计充值金额
                            'update_time' => $t
                        ]);
                    if ($result > 0) {
                        return $this->success('扣减账号可用余额-成功', $result);
                    }else{
                        return $this->success('扣减账号可用余额-失败', $result);
                    }
                }else{
                    return $this->error('未查询到审核信息');
                }
            } else {
                return $this->error('审核数据更新失败');
            }
        }else{
            return $this->error('审核失败：更新提现申请单状态错误');
        }
    }

    /**
     * 获取用户自己的提现信息--支持动态分页
     * @param int $user_id 当前用户ID
     * @param int $create_time_day 数据创建时间--日期
     * @param int $page 获取第几页的数据
     * @param int $size 分页尺寸;只支持，5,10,20分页尺寸
     * @return array 返回推荐任务的数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserAccountCostForPage(int $user_id,int $create_time_day = 0,int $page, int $size = 10): array
    {
        if(empty($user_id)){
            return $this -> error('用户ID必传');
        }
        $currentStart  = 0 ;
        $currentEnd  = 0 ;
        if ($size < 10) {
            $size = 10;
        }
        if($size != 10 && $size != 20 && $size != 5){
            $size = 10;
        }
        if ($page <= 0) {
            $page = 0;
            $currentEnd  = $size ;
        }else{
            if($page > 50){
                $page = 50;
            }
            $currentStart  = $page * $size;
            $currentEnd  = $currentStart + $size;
        }
        $create_time_day = 0;
        $today = date('Ymd');
        if(empty($create_time_day)){
            $create_time_day = $today -7;
        }
        if($create_time_day == $today){
            $create_time_day = $create_time_day -7;
        }
        $where =[
            ['user_id','=', $user_id],
            ['create_time_day','>=', $create_time_day],
        ];
        $userModel = new ModelUserAccountCost();
        $list = $userModel -> where($where)
            ->field('*')
            ->page($page,$size)
            -> select();
        //dump($page,$size,$userModel -> getLastSql());die();
        if(empty($list)){
            return $this->error('暂无提现记录');
        }else{
            foreach ($list as &$value){
                if(!empty($value['status'])){
                    $status = '';
                    //提现申请的状态: 1 待审核; 2 驳回; 3 待付款; 4 已付款;
                    switch($value['status']){
                        case '1':
                            $status = '待审核';
                            break;
                        case '2':
                            $status = '驳回';
                            break;
                        case '3':
                            $status = '待付款';
                            break;
                        case '4':
                            $status = '已到账'; //余额升级VIP，自动就是4 已到账
                            break;
                        default:
                            $status = '未知';
                            break;
                    }
                    $value['status_name'] = $status;
                    //消费类型
                    $cost_type_name = '';
                    if($value['cost_type'] == 1){
                        $cost_type_name = '提现';
                    }else{
                        $cost_type_name = '余额升级VIP';
                    }
                    $value['cost_type_name'] = $cost_type_name;

                    //卡片类型名称
                    $my_card_type_name = '';
                    //我的收款类型:0:未知，101 银行卡,201 微信，301 支付宝；
                    switch($value['my_card_type']){
                        case '101':
                            $my_card_type_name = '银行卡';
                            break;
                        case '201':
                            $my_card_type_name = '微信';
                            break;
                        case '301':
                            $my_card_type_name = '支付宝';
                            break;
                        default:
                            $my_card_type_name = '余额充值';
                            break;
                    }
                    $value['my_card_type_name'] = $my_card_type_name;
                }
            }
            return $this->success('成功', $list);
        }
    }


    /**
     * 获取用户自己的提现信息--支持动态分页
     * @param int $user_id 当前用户ID
     * @param int $income_time_day 收入日期，格式20210425
     * @param int $page 获取第几页的数据
     * @param int $size 分页尺寸;只支持，5,10,20分页尺寸
     * @return array 返回推荐任务的数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserAccountIncomeForPage(int $user_id,int $income_time_day=0,int $page, int $size = 10): array
    {
        if(empty($user_id)){
            return $this -> error('用户ID必传');
        }
        if(empty($income_time_day)){
            $income_time_day = date('Ymd') -7;
        }
        if($income_time_day == date('Ymd')){
            $income_time_day = $income_time_day -7;
        }
        $currentStart  = 0 ;
        $currentEnd  = 0 ;
        if ($size < 10) {
            $size = 10;
        }
        if($size != 10 && $size != 20 && $size != 5){
            $size = 10;
        }
        if ($page <= 0) {
            $page = 0;
            $currentEnd  = $size ;
        }else{
            if($page > 50){
                $page = 50;
            }
            $currentStart  = $page * $size;
            $currentEnd  = $currentStart + $size;
        }
        $userModel = new ModelUserAccountIncome();
        $where =[
            ['user_id','=', $user_id],
            ['income_time_day','>=', $income_time_day],
        ];
        $list = $userModel -> where($where)
            ->field('*')
            ->page($page,$size)
            -> select();
        //dump($page,$size,$userModel -> getLastSql());die();
        if(empty($list)){
            return $this->success('成功', $list);
        }else{
            foreach ($list as &$value){
                if(!empty($value['profit_type'])){
                    $profit_type = '';
                    //收益类型: 101:充值；201:任务；301:推广；401:团队
                    switch($value['profit_type']){
                        case '101':
                            $profit_type = '充值收益';
                            break;
                        case '201':
                            $profit_type = '任务完成收益';
                            break;
                        case '301':
                            $profit_type = '推广收益';
                            break;
                        case '401':
                            $profit_type = '团队收益';
                            break;
                        default:
                            $profit_type = '未知';
                            break;
                    }
                    $value['profit_type_name'] = $profit_type;
                }
                $number= '';
                if(!empty($value['account_recharge_id'])){ //充值收益id
                    $number= 'R-'.$value['account_recharge_id'];
                }elseif(!empty($value['account_task_complete_id'])){ //任务完成收益id
                    $number= 'C-'.$value['account_task_complete_id'];
                }elseif(!empty($value['account_popularize_id'])){ //推广收益id
                    $number= 'p-'.$value['account_popularize_id'];
                }elseif(!empty($value['account_team_id'])){ //团队收益id
                    $number= 'T-'.$value['account_team_id'];
                }
                $value['number'] =$number;
                $value['status'] ='已到账'; //收入表的数据都是经过审核后的
                $value['my_card_type_name'] ='系统账号'; //为了兼容支付接口增加的字段
            }
            return $this->success('成功', $list);
        }
    }

    /**
     * 增加用户收入
     * @param int $user_id 用户ID
     * @param string $balance 收益金额
     * @param int $type 业务类型ID
     * @return array
     */
    public function addUserAccountBalance(int $user_id,string $balance,int $type) : array
    {
        if (empty($user_id) || empty($balance)) {
            return $this->error('参数错误');
        }
        switch ($type) {
            case 101:
                $field_name = 'recharge_profit'; //充值累计金额
                 break;
            case 201:
                $field_name = 'total_task_profit'; //任务累计收益
                break;
            case 301:
                $field_name = 'total_popularize_profit'; //推广累计收益
                break;
            case 401:
                $field_name = 'team_profit'; //团队累计收益
                break;
            default:
                $field_name = 'recharge_profit';
                break;
        }
        $modelUserAccount = new ModelUserAccount();
        $where = [
            'user_id' => $user_id,
        ];
        $data = [
            'total' => Db::raw('total + ' . $balance),
            'balance' => Db::raw('balance + ' . $balance),
            $field_name => Db::raw($field_name.' + ' . $balance),
            'update_time' => time(),
        ];
        $result = $modelUserAccount->where($where)->update($data);
        //dump($modelUserAccount-> getLastSql());die();
        if (!empty($result)) {
            return $this->success('成功', $result);
        } else {
            return $this->error('更新用户账号余额');
        }
    }

}